<?php
namespace  app\models;
require_once 'BaseModel.php';

class Configs extends BaseModel{
	
	public static function genRandKey(){
		return strtoupper(md5(time() . mt_rand(0, 10000) . substr('abcdefg', mt_rand(0, 7))));
	}

	public static function getConfigByAppkey($appkey){
        //$appkey = mysql_real_escape_string($appkey);
		$con = self::pdo_con();
		$sql = "select * from configs where appkey ='{$appkey}' order by id asc limit 1;";
		foreach ($con->query($sql) as $row) {
			return $row;
		}
		return null;
	}

	public static function getAllConfig(){
		$con = self::pdo_con();
		$sql = "select * from configs";
		$config = array();
		foreach ($con->query($sql) as $row) {
			$config[] = $row;
		}
		return $config;
	}
	//主持业务系统
	public static function register($appname,$description,$domains,$usertypes){
		$appname = mysql_real_escape_string($appname);
		$description = mysql_real_escape_string($description);
		$domains = mysql_real_escape_string($domains);
		$usertypes = mysql_real_escape_string($usertypes);
		$appkey=self::genRandKey();
		$secret=self::genRandKey();
		$con = self::pdo_con();
		$now = date('Y-m-d H:i:s');
		$sql = "select * from configs  where appname='{$appname}'";
		$items=$con->query($sql) ;

		//验证系统名称是否存在
		if($items->rowCount ()>0)
		{
			return null;
		}
		$sql = "INSERT INTO configs ( appname, appkey, domains, description, secret, type, created_at ) VALUES".
					"(  '{$appname}', '{$appkey}','{$domains}', '{$description}', '{$secret}', '{$usertypes}', '{$now}' )";
		$con->exec($sql);
		$id=$con->lastInsertId();
		//$idQuery="SELECT LAST_INSERT_ID()";
		//$id=$con->exec($idQuery);
		return $id;
	}


	public  static function getConfig($id)
	{
		$configid = intval($id);
		$con = self::pdo_con();
		$sql = "select * from configs  where id={$configid}";
		foreach ($con->query($sql) as $row) {
		  return  $row;
		}
		return null;
	}
}
